package com.tianji.learning.controller;

import com.tianji.common.domain.dto.PageDTO;
import com.tianji.common.domain.query.PageQuery;
import com.tianji.common.utils.BeanUtils;
import com.tianji.common.utils.ObjectUtils;
import com.tianji.common.utils.UserContext;
import com.tianji.learning.entity.LearningLesson;
import com.tianji.learning.service.ILearningLessonService;
import com.tianji.learning.vo.LearningLessonVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.bind.annotation.RestController;

/**
 * <p>
 * 学生课程表 前端控制器
 * </p>
 *
 * @author tj-learning
 * @since 2023-05-25
 */
@RestController
@RequestMapping("/lessons")
public class LearningLessonController {
    @Autowired
    private ILearningLessonService lessonService;

    /**
     * 分页查询
     * @param pageQuery
     * @return
     */
    @GetMapping("/page")
    public PageDTO pageQuery(PageQuery pageQuery){
        PageDTO pageDTO = lessonService.pageQuery(pageQuery);

        return pageDTO;
    }

    /**
     * 根据id查询课程学习状态
     * @param id
     * @return
     */
    @GetMapping("/{id}")
    public LearningLessonVO pageQuery(@PathVariable Long id){
        LearningLesson lesson = lessonService.lambdaQuery()
                .eq(LearningLesson::getCourseId,id)
                .eq(LearningLesson::getUserId,UserContext.getUser())
                .one();
        if (ObjectUtils.isEmpty(lesson)){
            return null;
        }
        LearningLessonVO lessonVO = BeanUtils.copyBean(lesson, LearningLessonVO.class);
        return lessonVO;
    }

    /**
     * 查询正在学习的课程
     * @return
     */
    @GetMapping("/now")
    public LearningLessonVO queryMyCurrentLesson(){
        LearningLessonVO lessonVO = lessonService.queryMyCurrentLesson();

        return lessonVO;
    }

    /**
     * 校验当前用户是否可以学习当前课程
     * @param courseId
     * @return
     */
    @GetMapping("/{courseId}/valid")
    public Long isLessonValid(@PathVariable("courseId") Long courseId){
        return lessonService.isLessonValid(courseId);
    }

    /**
     * 统计课程学习人数
     * @param courseId 课程id
     * @return 学习人数
     */
    @GetMapping("/{courseId}/count")
    public Integer countLearningLessonByCourse(@PathVariable("courseId") Long courseId){
        Integer count = lessonService.lambdaQuery().eq(LearningLesson::getCourseId, courseId).count();
        return count;
    }
}
